﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        IniFile IniFile = new IniFile(string.Format("{0}\\" + "config.ini", Application.StartupPath));
        private DataTable dataTable;

        public Form1()
        {
            InitializeComponent();
        }
        private async void AliyunDriveSignIn()
        {
            try
            {
                int successcount = 0;
                foreach (DataRow row in dataTable.Rows)
                {
                    string refreshToken = row["Token"].ToString();
                    string receivedString = "False"; // 默认设置为未领取，0 表示未领取
                    if (row["Received"] != null && row["Received"] != DBNull.Value)
                    {
                        receivedString = Convert.ToString(row["Received"]);
                    }
                    if (!string.IsNullOrEmpty(refreshToken))
                    {
                        using (HttpClient client = new HttpClient())
                        {
                            // 刷新token获取access_token
                            HttpResponseMessage response = await client.PostAsync("https://auth.aliyundrive.com/v2/account/token",
                                new StringContent($@"{{""grant_type"": ""refresh_token"", ""refresh_token"": ""{refreshToken}""}}", Encoding.UTF8, "application/json"));

                            if (!response.IsSuccessStatusCode)
                            {
                                AppendTextToFirstLine("refresh_token错误，请重新填写refresh_token");
                            }
                            else
                            {
                                string responseJson = await response.Content.ReadAsStringAsync();
                                dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(responseJson);
                                string accessToken = data.access_token;

                                if (string.IsNullOrEmpty(accessToken))
                                {
                                    AppendTextToFirstLine("获取access_token失败");
                                }
                                else
                                {
                                    try
                                    {
                                        // 进行签到
                                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

                                        HttpResponseMessage signInResponse = await client.PostAsync("https://member.aliyundrive.com/v1/activity/sign_in_list",
                                            new StringContent(@"{""_rx-s"": ""mobile""}", Encoding.UTF8, "application/json"));
                                        string signInResponseJson = await signInResponse.Content.ReadAsStringAsync();
                                        dynamic signInData = Newtonsoft.Json.JsonConvert.DeserializeObject(signInResponseJson);
                                        int signInCount = signInData.result.signInCount;
                                        string message = "";
                                        if (Convert.ToBoolean(receivedString))
                                        {
                                            // 领取奖励
                                            HttpResponseMessage rewardResponse = await client.PostAsync("https://member.aliyundrive.com/v1/activity/sign_in_reward?_rx-s=mobile",
                                                new StringContent($@"{{""signInDay"": {signInCount}}}", Encoding.UTF8, "application/json"));
                                            string rewardResponseJson = await rewardResponse.Content.ReadAsStringAsync();
                                            dynamic rewardData = Newtonsoft.Json.JsonConvert.DeserializeObject(rewardResponseJson);
                                            string rewardName = rewardData.result.name;
                                            string rewardDescription = rewardData.result.description;
                                            // 构建签到成功和获得奖励的信息
                                            message = $"账号：{data.user_name}，签到成功，本月累计签到{signInCount}天，获得奖励：{rewardName}，{rewardDescription}";
                                        }
                                        else
                                        {
                                            message = $"账号：{data.user_name}，签到成功，本月累计签到{signInCount}天";
                                        }

                                        AppendTextToFirstLine(message);
                                        successcount++;
                                    }
                                    catch
                                    {
                                        AppendTextToFirstLine("签到或领取奖励失败");
                                    }
                                }
                            }
                        }
                    }
                }
                if (cbisexit.Checked && successcount > 0)
                {
                    AppendTextToFirstLine(DateTime.Now.ToLocalTime() + " 签到成功，30秒后将退出程序");
                    Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith((task) =>
                    {
                        // 在倒计时结束后退出应用程序
                        Environment.Exit(0);
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitializeDataGridView();
            LoadRefreshTokensFromINIFile();
            if (cbAuto.Checked)
            {
                AliyunDriveSignIn();
            }

            // 创建并设置工具提示控件
            ToolTip toolTip = new ToolTip();
            toolTip.SetToolTip(cbisexit, "如果没有出现错误，勾选了此项后， 将在30秒后自动退出此程序。");
            toolTip.SetToolTip(cbAuto, "打开此程序时，将自动签到。");
            toolTip.SetToolTip(btnSaveini, "可以手动修改配置文件，在此程序目录下：config.ini");
        }

        private void InitializeDataGridView()
        {
            dataGridView1.RowHeadersVisible = false;
            dataTable = new DataTable();
            dataTable.Columns.Add("Token", typeof(string));
            dataTable.Columns.Add("Received", typeof(bool));

            dataGridView1.DataSource = dataTable;
            // 设置列宽度
            dataGridView1.Columns["Token"].Width = 200; // 第一列宽度设置为 200 像素
            dataGridView1.Columns["Received"].Width = 100; // 第二列宽度设置为 100 像素

            // 设置列 HeaderText
            dataGridView1.Columns["Token"].HeaderText = "refresh_token值";
            dataGridView1.Columns["Received"].HeaderText = "是否领取奖励";
        }
        public void LoadRefreshTokensFromINIFile()
        {
            var val = IniFile.ReadString("Tokens", "Token", "refresh_token1#False");
            var isExit = IniFile.ReadBoolean("AutoExit", "AutoExit", true);
            var AutoSign = IniFile.ReadBoolean("AutoSign", "AutoSign", true);
            cbisexit.Checked = isExit;
            cbAuto.Checked = AutoSign;
            string[] lines = val.Split(',');
            foreach (var line in lines)
            {
                string[] tokenParts = line.Split('#');
                if (tokenParts.Length == 2)
                {
                    string tokenValue = tokenParts[0].Trim();
                    bool received = true; // 默认设置为未领取，0 表示未领取
                    string receivedString = tokenParts[1].Trim();

                    if (!string.IsNullOrEmpty(receivedString))
                    {
                        received = Convert.ToBoolean(receivedString);
                    }
                    dataTable.Rows.Add(tokenValue, received);
                }
            }
        }

        public void SaveRefreshTokensToINIFile()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (DataRow row in dataTable.Rows)
                {
                    string tokenValue = row["Token"].ToString();
                    string receivedString = "False"; // 默认设置为未领取，0 表示未领取
                    if (row["Received"] != null && row["Received"] != DBNull.Value)
                    {
                        receivedString = Convert.ToString(row["Received"]);
                    }

                    sb.AppendFormat("{0}#{1},", tokenValue, receivedString);
                }
                IniFile.WriteString("Tokens", "Token", sb.ToString().TrimEnd(','));

                IniFile.WriteBoolean("AutoExit", "AutoExit", cbisexit.Checked);
                IniFile.WriteBoolean("AutoSign", "AutoSign", cbAuto.Checked);
                MessageBox.Show("保存配置成功。");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存INI文件时出错：" + ex.Message);
            }
        }
        private void btnSaveini_Click(object sender, EventArgs e)
        {
            SaveRefreshTokensToINIFile();
        }




        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://www.8kmm.com/bookmark/?wd=%E9%98%BF%E9%87%8C%E4%BA%91%E7%9B%98%E5%A6%82%E4%BD%95%E5%BE%97%E5%88%B0refresh_tokens&t=baidu");
        }

        private void btnSign_Click(object sender, EventArgs e)
        {
            AliyunDriveSignIn();
        }

        public void AppendTextToFirstLine(string text)
        {
            rtbInfo.SelectionStart = 0; // 设置插入点在第一行开头
            rtbInfo.SelectionLength = 0;
            rtbInfo.SelectedText = text; // 在插入点处插入文本
        }
    }

}
